﻿#region 命名空间

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using WinnerCMS.Common;

#endregion

namespace WinnerCMS.BLL.PageFactory.TagModule
{
    /// <summary>
    /// 标签解释引擎
    /// </summary>
    public class TagEngine
    {
        /// <summary>
        /// 标签正则表达式
        /// </summary>
        private const string 标签正则表达式 = @"<TW:{0}(.*?)>([\S\s]*?)</TW:{0}>";

        /// <summary>
        /// 属性正则表达式
        /// </summary>
        private const string 属性正则表达式 = @"\s*{0}\s*=\s*""*(.*?)""*[\s|>*]";

        private static readonly Regex 属性名表达式 = new Regex(@"\s*(\w+)\s*=",
            RegexOptions.Compiled | RegexOptions.IgnoreCase);

        #region 标签是否存在

        /// <summary>
        /// 标签是否存在
        /// </summary>
        /// <param name="TabName"></param>
        /// <param name="InPut"></param>
        /// <returns></returns>
        public static bool Exists(string TabName, string InPut)
        {
            string startTag = string.Concat("<TW:", TabName);
            string endTag = string.Concat("</TW:", TabName, ">");

            int s = InPut.IndexOf(startTag, StringComparison.CurrentCultureIgnoreCase);
            int e = InPut.IndexOf(endTag, StringComparison.CurrentCultureIgnoreCase);


            return (s > 0 && e > 0);
        }

        #endregion

        #region 属性的值

        /// <summary>
        /// 属性的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strAnalysed"></param>
        /// <param name="strproperty"></param>
        /// <returns></returns>
        public static T GetValue<T>(string strAnalysed, string strproperty)
        {
            string str = MyString.GetString(strAnalysed, "<TW:", ">");

            Match match = new Regex(string.Format(属性正则表达式, strproperty), RegexOptions.IgnoreCase).Match(str);

            string values = match.Groups[1].Value;
            if (
                (typeof (T) == typeof (int)
                 || typeof (T) == typeof (byte)
                 || typeof (T) == typeof (short)
                 || typeof (T) == typeof (long))
                && values.Length == 0)
            {
                values = "0";
            }
            if (typeof (T) == typeof (bool) && values.Length == 0)
            {
                values = "false";
            }
            return (T) Convert.ChangeType(values, typeof (T));
        }

        /// <summary>
        /// 属性的值
        /// </summary>
        /// <param name="strAnalysed">被分析的字符串</param>
        /// <param name="strproperty">要取哪个属性</param>
        /// <returns></returns>
        public static string GetValue(string strAnalysed, string strproperty)
        {
            string str = MyString.GetString(strAnalysed, "<TW:", ">");

            Match match = new Regex(string.Format(属性正则表达式, strproperty), RegexOptions.IgnoreCase).Match(str);

            return match.Groups[1].Value;
        }


        /// <summary>
        /// 属性的值
        /// </summary>
        /// <param name="strAnalysed">被分析的字符串</param>
        /// <param name="strTab">要取哪个标签</param>
        /// <param name="strproperty">要取哪个属性</param>
        /// <returns></returns>
        public static T GetValue<T>(string strAnalysed, string strTab, string strproperty)
        {
            string str = GetString(strAnalysed, strTab, GetWhich.All);

            str = MyString.GetString(str, "<TW:", ">");

            Match match = new Regex(string.Format(属性正则表达式, strproperty), RegexOptions.IgnoreCase).Match(str);

            string values = match.Groups[1].Value;
            if ((typeof (T) == typeof (int)
                 || typeof (T) == typeof (byte)
                 || typeof (T) == typeof (short)
                 || typeof (T) == typeof (long))
                && values.Length == 0)
            {
                values = "0";
            }
            return (T) Convert.ChangeType(values, typeof (T));
        }

        #endregion

        public static string ReplaceName(string analysed, string sqlString)
        {
            var Ms = 属性名表达式.Matches(analysed);
            foreach (Match m in Ms)
            {
                string Name = m.Groups[1].Value;
                string Value = GetValue(analysed, Name);


                try
                {
                    Convert.ToInt32(Value);
                    sqlString = sqlString.Replace("@" + Name, Value);
                }
                catch
                {
                    sqlString = sqlString.Replace("@" + Name, "'" + Value + "'");
                }
            }
            return sqlString;
        }

        #region 获得标签内的值

        /// <summary>
        /// 获得标签内的值
        /// </summary>
        /// <param name="strAnalysed">被分析的字符串</param>
        /// <param name="strTab">要取哪个标签</param>
        /// <param name="which">获得标签内的值的种类</param>
        /// <returns></returns>
        public static string GetString(string strAnalysed, string strTab, GetWhich which)
        {
            string strtemp = string.Format(标签正则表达式, strTab);
            Match match = new Regex(strtemp, RegexOptions.IgnoreCase).Match(strAnalysed);

            if (which == GetWhich.All)
            {
                return match.Groups[0].Value.Trim();
            }
            if (which == GetWhich.InnerTemplate)
            {
                return match.Groups[2].Value.Trim();
            }
            string temp = match.Groups[0].Value;
            match = new Regex(string.Format(@"<{0}>([\S\s]*?)</{0}>", which), RegexOptions.IgnoreCase).Match(temp);

            return match.Groups[1].Value.Trim();
        }

        /// <summary>
        /// 获得智能标签内的模板列的值
        /// </summary>
        /// <param name="strAnalysed"></param>
        /// <param name="strTab"></param>
        /// <param name="which"></param>
        /// <returns></returns>
        /// <remarks>专门处理GetString不完全支持的非智能模板</remarks>
        public static string GetInnerModule(string strAnalysed, string strTab, GetWhich which)
        {
            //string strtemp = string.Format(@"<{0}>([\S\s]*?)</{0}>", strTab);
            //Match match = new Regex(strtemp, RegexOptions.IgnoreCase).Match(strAnalysed);

            if (which == GetWhich.All)
            {
                return MyString.GetString(strAnalysed, string.Format("<{0}>", strTab), string.Format("</{0}>", strTab));
                //return match.Groups[0].Value;
            }
            return MyString.GetInnerString(strAnalysed, string.Format("<{0}>", strTab), string.Format("</{0}>", strTab));
            //return match.Groups[1].Value;
        }

        #endregion

        #region 取得标签列表

        /// <summary>
        /// 取得标签列表
        /// </summary>
        /// <param name="strAnalysed">被分析的字符串</param>
        /// <returns></returns>
        public IList<string> GetTabList(string strAnalysed)
        {
            IList<string> list = new List<string>();
            string strtemp = string.Format(标签正则表达式, "");
            Match match = new Regex(strtemp, RegexOptions.IgnoreCase).Match(strAnalysed);

            foreach (Match m in match.Groups)
            {
                list.Add(m.Value);
            }

            return list;
        }

        #endregion

        #region 模板标签集合

        public static IList<string> TagCollection(string webHtml)
        {
            const string pattern = @"<TW:(.*?)</TW:\w+>";
            Match match = new Regex(pattern, RegexOptions.IgnoreCase).Match(webHtml);

            return (from Match m in match.Groups select m.Value).ToArray();
        }

        /// <summary>
        /// 模板标签集合
        /// </summary>
        /// <param name="webHtml"></param>
        /// <param name="tabName"></param>
        /// <returns></returns>
        public static IList<string> TagCollection(string webHtml, string tabName)
        {
            IList<string> list = new List<string>();

            int startpoint = 0;
            string startTag = string.Format("<TW:{0}", tabName);
            string endTag = string.Format("</TW:{0}>", tabName);
            do
            {
                int s = webHtml.IndexOf(startTag, startpoint, StringComparison.CurrentCultureIgnoreCase);
                if (s < 0) return list;

                int e = webHtml.IndexOf(endTag, s, StringComparison.CurrentCultureIgnoreCase) + endTag.Length;

                startpoint = webHtml.IndexOf(startTag, e, StringComparison.CurrentCultureIgnoreCase);

                if ((e - s) < 0)
                {
                    return list;
                }

                list.Add(webHtml.Substring(s, e - s));
            } while (startpoint > -1);

            return list;
        }

        #endregion

        #region 替换全局变量

        /// <summary>
        /// 替换全局变量
        /// </summary>
        /// <param name="TempStrBuilder"></param>
        /// <param name="ModelId"></param>
        public static void ReplaceM(StringBuilder TempStrBuilder, byte ModelId)
        {
            if (ModelId != 0)
            {
                TempStrBuilder.Replace("{ModelPath}", StaticFilePath.ModelHtmlPath(ModelId));

                TempStrBuilder.Replace("{ChannelSpecialIndexURL}", StaticFilePath.SpecialIndexUrl(ModelId));
            }
            TempStrBuilder.Replace("{TemplatePath}", StaticFilePath.TemplatePath);
            TempStrBuilder.Replace("{SysPath}", StaticFilePath.SysPath);
            TempStrBuilder.Replace("{StylePath}", StaticFilePath.StylePath);
            TempStrBuilder.Replace("{IndexURL}", StaticFilePath.IndexUrl());
            TempStrBuilder.Replace("{GuestBookURL}", StaticFilePath.GuestBookUrl());
            TempStrBuilder.Replace("{SiteName}", WebConfig.SiteName);
        }

        #endregion
    }
}